# app/routes/user.py
import json
import time
from app import jwt, jwt_required, create_access_token
from flask import Blueprint, request, jsonify, g, make_response
from app.services.user_service import UserService
from app.utils.decrpy import Rsa
from app.utils.sendcode import sned
from app.utils.randomNumber import randomNumber
from app import redis_store
from functools import wraps
user = Blueprint('user', __name__)
user_service = UserService()
RSA = Rsa()


@jwt.unauthorized_loader
def unauthorized_response(callback):

    return jsonify({
        'code': 401,
        'msg': '登录信息过期',
        'error': 'custom_unauthorized_error',
        'message': 'Custom error message for unauthorized access'
    })

@user.before_request
def authenticate_user():
    # 在这里进行用户身份验证逻辑
    # 例如，检查用户的登录状态、权限等
    # 如果验证失败，可以返回特定的响应或者抛出异常
    # 如果验证成功，可以继续处理请求
    # 解密签名， 签名异常记录ip
    data = request.data
    try:
        data = json.loads(RSA.decrypt_message(data))
        print(int(time.time()) - data['timestamp'])
        if int(time.time()) - data['timestamp'] >= 60:
            return make_response(jsonify({'error': '签名认证过期', 'code': 404}))
    except:
        return make_response(jsonify({'error': '签名认证失败', 'code': 404}))
    # g.authenticated_result = data  # 使用 Flask 的上下文存储返回值
    g.authenticated_result = data
    # return func()


@user.route('/api/login', methods=['POST'])
def login():
    request_from = g.authenticated_result
    username = request_from['username']
    redis_code = redis_store.get(username).decode('utf-8')
    if redis_code:
        if redis_code == request_from['code']:
            access_token = create_access_token(identity=request_from['username'])
            return jsonify(code=200, data={'token': access_token}, msg='登录成功')
        else:
            return jsonify(code=404, data={'token': ''}, msg='验证码错误')
    else:
        return jsonify(code=404, data={'token': ''}, msg='验证码已过期')
    # if user_service.find_user_by_username(request_from['username'], request_from['password']):
    #
    #     return jsonify(code=200, data={'token': access_token}, msg='登录成功')
    # else:
    #     return jsonify(code=404, data={'token': ''}, msg='用户名或密码错误')


@user.route('/api/test', methods=['POST'])
@jwt_required()
def test():
    return jsonify(code=200, msg='测试成功')


@user.route('/api/sendcode', methods=['post'])
def sendCode():
    request_from = g.authenticated_result
    phone = request_from['phone']
    # 检查号码是否合格
    code = randomNumber()
    print('code: ', code)
    sned(code, phone)
    redis_store.set(phone, code, ex=300)
    return jsonify(code=200, data={}, msg='发送成功')

